var express = require("express");
var router = express.Router();
var mongoose = require("mongoose");
const multiparty = require("multiparty")
const fs = require("fs")
const xlsx = require("node-xlsx")
var { orderModel } = require("../db/order_model");
var { rideruserModel } = require("../db/rider");
var { userModel } = require("../db/user_model");
var { goodModer } = require("../db/goods_model");
router.get("/orderFind", async function (req, res) {
  // console.log(obj,'obj');
  let uname = req.query.uname;
  let rname = req.query.rname;
  let statue = req.query.statue;
  let startTime = req.query.startTime;
  let endTime = req.query.endTime;
  let currentPage = req.query.currentPage;
  let pageSize = req.query.pageSize;
  let rid = [];
  let uid = [];
  let obj = {};
  if (uname != " ") {
    let data1 = await userModel.find({
      $or: [{ nickName: RegExp(uname) }, { mobile: uname }],
    });
    data1.map((item) => uid.push(item._id));
    obj.uid = { $in: uid };
  }
  if (rname != " " ) {
    let data1 = await rideruserModel.find({ username: RegExp(rname) });
    data1.map((item) => rid.push(item._id));
    obj.rid = { $in: rid };
  }
  if (statue != "all" && statue) {
    obj.statue = statue;
  }
  if (startTime && endTime) {
    obj.place = { $gte: startTime, $lte: endTime };
  }
  if (startTime && endTime == "") {
    obj.place = { $gte: startTime };
  }
  if (endTime && startTime == "") {
    obj.place = { $lte: endTime };
  }
  console.log(obj, "obj");
  let data = await orderModel
    .find(obj)
    .populate("rid")
    .populate("uid")
    .skip((currentPage - 1) * pageSize)
    .limit(pageSize);
  let user = await orderModel.find(obj);
  res.send({
    code: 200,
    data,
    total: user.length,
  });
});
router.get("/settlementFind", async function (req, res) {
  let rname = req.query.name;
  let phone = req.query.phone;
  let done = req.query.statue;
  let startTime = req.query.startTime;
  let endTime = req.query.endTime;
  let currentPage = req.query.currentPage;
  let pageSize = req.query.pageSize;
  let rid = [];
  let obj = { statue: "已完成" };
  if (rname != "" && phone != "") {
    let data1 = await rideruserModel.find({ username: RegExp(rname)});
    data1.map((item) => rid.push(item._id));
    obj.rid = { $in: rid };
  } else if (phone != "") {
    let data1 = await rideruserModel.find({ phone: phone });
    data1.map((item) => rid.push(item._id));
    obj.phones = { $in: rid };
  } else if (rname != "") {
    let data1 = await rideruserModel.find({ username: RegExp(rname) });
    data1.map((item) => rid.push(item._id));
    obj.phones = { $in: rid };
  }
  if (done != "all" && done) {
    obj.done = done;
  }
  if (startTime && endTime) {
    console.log(2222);
    obj.place = { $gte: startTime, $lte: endTime };
  }
  if (startTime && endTime == "") {
    obj.place = { $gte: startTime };
  }
  if (endTime && startTime == "") {
    obj.place = { $lte: endTime };
  }
  let data = await orderModel
    .find(obj)
    .populate("rid")
    .populate("uid")
    .skip((currentPage - 1) * pageSize)
    .limit(pageSize);
  let user = await orderModel.find(obj);
  console.log(obj, "data");
  res.send({
    code: 200,
    data,
    total: user.length,
  });
});
router.post("/editStatue", async function (req, res) {
  let id = req.query.id;
  let statue = req.query.status;
  await orderModel.updateOne({ _id: id }, { statue: statue });
  res.send({
    code: 200,
    msg: "修改成功",
  });
});
router.get("/edit/:id", async function (req, res) {
  let id = req.params.id;
  await orderModel.updateOne({ _id: id }, { done: "已支付" });
  res.send({
    code: 200,
    msg: "修改成功",
  });
});

router.get("/orderFindUser", async function (req, res) {
  // console.log(obj,'obj');
  let id = req.query.id;
  let statue = req.query.statue;
  let currentPage = req.query.currentPage;
  let pageSize = req.query.pageSize;
  let obj = {};
  if (id !='') {
    obj.uid = id;
  }
  if (statue != "all") {
    obj.statue = statue;
  }
  console.log(obj, "obj");
  let data = await orderModel
    .find(obj)
    .populate("uid")
    .skip((currentPage - 1) * pageSize)
    .limit(pageSize);
  let user = await orderModel.find(obj)
  res.send({
    code: 200,
    data,
    total: user.length,
  });
});
router.get("/orderFindlist", async function (req, res) {
  // console.log(obj,'obj');
  let uname = req.query.uname;
  let rname = req.query.rname;
  let statue = req.query.statue;
  let startTime = req.query.startTime;
  let endTime = req.query.endTime;
  let currentPage = req.query.currentPage;
  let pageSize = req.query.pageSize;
  let rid = [];
  let uid = [];
  let obj = {};
  if (uname != " ") {
    let data1 = await userModel.find({
      $or: [{ nickName: RegExp(uname) }, { mobile: uname }],
    });
    data1.map((item) => uid.push(item._id));
    obj.uid = { $in: uid };
  }
  if (rname != " ") {
    let data1 = await rideruserModel.find({ username: RegExp(rname) });
    data1.map((item) => rid.push(item._id));
    obj.rid = { $in: rid };
  }
  if (statue != "all") {
    obj.statue = statue;
  }
  if (startTime && endTime) {
    console.log(2222);
    obj.place = { $gte: startTime, $lte: endTime };
  }
  if (startTime && endTime == "") {
    obj.place = { $gte: startTime };
  }
  if (endTime && startTime == "") {
    obj.place = { $lte: endTime };
  }
  // console.log(obj, "obj");
  let data = await orderModel
    .find(obj)
    .populate("rid")
    .populate("uid")
    .skip((currentPage - 1) * pageSize)
    .limit(pageSize);
  let user = await orderModel.find(obj);
  res.send({
    code: 200,
    data,
    total: user.length,
  });
});
router.get("/editdo/:id", async function (req, res) {
  let id = req.params.id;
  let rider_pikup = new Date()

  await orderModel.updateOne({ _id: id }, { statue: "已完成",rider_pikup:rider_pikup });
  res.send({
    code: 200,
    msg: "已完成",
  });
});

router.get("/editcancel/:id", async function (req, res) {
  let id = req.params.id;
  await orderModel.updateOne({ _id: id }, { statue: "已取消" });
  res.send({
    code: 200,
    msg: "已取消",
  });
});

router.get("/editRebuy/:id", async function (req, res) {
  let id = req.params.id;
  await orderModel.updateOne({ _id: id }, { statue: "待接单" });
  res.send({
    code: 200,
    msg: "待接单",
  });
});
router.get("/buy/:id", async function (req, res) {
  let id = req.params.id;
  await orderModel.updateOne({ _id: id }, { statue: "进行中" });
  res.send({
    code: 200,
    msg: "进行中",
  });
});

router.get("/editprice", async function (req, res) {
  let id = req.query.id;
  let price = req.query.price;
  console.log(id, price);
  await orderModel.updateOne({ _id: id }, { $set: { cost: price } });
  res.send({
    code: 200,
    msg: "进行中",
  });
});

router.delete("/delList/:id", async function (req, res) {
  let id = req.params.id;
  await orderModel.deleteOne({ _id: id });
  res.send({
    code: 200,
    msg: "删除成功",
  });
});
router.post("/EditMany", async function (req, res) {
  let data = req.query.arr;

  data.map((item) => mongoose.Types.ObjectId(item));
  console.log(data, "data");
  await orderModel.updateMany(
    { _id: { $in: data } },
    { $set: { done: "已支付" } }
  );
  res.send({
    code: 200,
    msg: "结算成功",
  });
});

// 添加订单
router.post("/add_order", async (req, res) => {
  let body = req.body;
  console.log(`body`, body);
  await orderModel.create(body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});

router.get("/riderorderFind", async function (req, res) {
  // console.log(obj,'obj');
  let statue = req.query.statue;
  let rid = req.query.rid;
  let currentPage = req.query.currentPage;
  let pageSize = req.query.pageSize;
  if (rid) {
    let data = await orderModel
      .find()
      .skip((currentPage - 1) * pageSize)
      .limit(pageSize)
      .where({
        statue: statue,
        rid: rid,
      });
    res.send({
      code: 200,
      msg: "展示成功",
      data,
      total: data.length,
    });
  } else {
    let data = await orderModel
      .find()
      .skip((currentPage - 1) * pageSize)
      .limit(pageSize)
      .where({
        statue: statue,
      });
    res.send({
      code: 200,
      msg: "展示成功",
      data,
      total: data.length,
    });
  }
  // console.log(obj, "obj");
});



// 修改订单
router.put("/edit_order/:id", async function (req, res) {
  let body = req.body;
  console.log(body);
  try {
    await orderModel.updateOne({ _id: req.params.id }, { $set: body });
    res.send({
      code: 200,
      msg: "修改成功",
    });
  } catch (err) {
    console.error("Failed to insert facility into MongoDB:", err);
    res.status(500).send({ error: "Server error" });
  }
});

module.exports = router;
